﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LL.Business;
using NanoERP.Model;
using NanoERP.Common;

namespace NanoERP.Business.BaseInfo
{
    /// <summary>
    /// 部门人员信息业务类
    /// </summary>
    public class UserinfoBLL : ServiceBase
    {
        /// <summary>
        /// 部门人员信息查询
        /// </summary>
        /// <param name="depatId">部门ID</param>
        /// <param name="query">查询关键字 支持：名称|编码|拼音码</param>
        /// <returns></returns>
        public List<Userinfo> Query(int depatId, string query)
        {
            var sql = string.Format(@"{0} ('{1}'='' OR USERPYM like '%{1}%' OR USERNO like '%{1}%' OR 
                                      USERPYM  like '%{1}%' )", query.Length == 0 ? "(@0=0 OR DEPTID=@0) AND" : "", query);

            var list = DbSession.Query<Userinfo>(sql, depatId).ToList();
            return list;
        }

        /// <summary>
        /// 部门人员信息
        /// </summary>
        /// <param name="id">部门人员信息ID</param>
        /// <returns></returns>
        public Userinfo Get(long id)
        {
            return this.DbSession.Get<Userinfo>(id);
        }

        /// <summary>
        /// 浏览记录 上一条 下一条
        /// </summary>
        /// <param name="id">浏览记录Id</param>
        /// <param name="type">类型 0-向上,1-向下</param>
        /// <param name="isLast">是否最后一条数据</param>
        /// <returns></returns>
        public Userinfo PreRecord(long id, int type, ref bool isLast)
        {
            var obj = DbSession.Get<Userinfo>(id);
            if (obj == null)
            {
                var dt = DbSession.ExcuteQuery(string.Format("select {0}(ID) as ID from dbo.Userinfo", type.Equals(0) ? "MIN" : "MAX"));
                var lId = dt.Rows.Count > 0 ? Normal.ToLong(dt.Rows[0][0]) : 0;

                isLast = type.Equals(0) ? id <= lId + 1 : id >= lId - 1;

                var list = DbSession.SqlQuery<Userinfo>(
                    string.Format("select top 1 * from dbo.Userinfo where ID {1} {0} Order by Id {2}",
                    isLast ? lId + (type.Equals(0) ? 1 : -1) : id, type.Equals(0) ? "<" : ">", type.Equals(0) ? "desc" : "asc"));

                obj = list.First();
            }

            return obj;
        }

        /// <summary>
        /// 编辑部门人员信息
        /// </summary>
        /// <param name="o"></param>
        public void Edit(Userinfo o)
        {
            var session = this.DbSession;
            if (o.Id == 0) session.Insert(o, "Id");
            else
                session.Update(o);
        }

        /// <summary>
        /// 删除部门人员信息
        /// </summary>
        /// <param name="id"></param>
        public void Delete(long id)
        {
            DbSession.Delete<Userinfo>(id);
        }
    }
}
